import React, { useReducer, useContext, useEffect } from 'react';
import GlobalContext, { TUser } from './context';

export const UPDATE_LANG = 'UPDATE_LANG';
export const UPDATE_ANTIFORGERY = 'UPDATE_ANTIFORGERY';
export const UPDATE_CURRENTINFO = 'UPDATE_CURRENTINFO';
export const UPDATE_NOTIFICATIONS = 'UPDATE_NOTIFICATIONS';
export const UPDATE_VIEWAS = 'UPDATE_VIEWAS';

const reducer = (state: any, action: any) => {
	switch (action.type) {
		case UPDATE_LANG:
			return { ...state, lang: action.state.lang };
		case UPDATE_ANTIFORGERY:
			return {
				...state,
				antiforgery: action.state.antiforgery,
				environment: action.state.environment,
				templates: action.state.templates,
				year: action.state.year
			};
		case UPDATE_CURRENTINFO:
			return {
				...state,
				userInfo: action.state.userInfo
			};
		case UPDATE_NOTIFICATIONS:
			return { ...state, isUpdated: { notifications: true } };
		case UPDATE_VIEWAS:
			return { ...state, viewAs: action.state.viewAs };
		default:
			return state;
	}
};

const Provider = (props: any) => {
	const context: any = useContext(GlobalContext);
	const [state, dispatch] = useReducer(reducer, context.state);

	useEffect(() => {
		let myUserInfo: TUser = {
			firstName: 'bran',
			lastName: 'gu',
			name: '',
			id: '',
			email: 'wuzinong@gmail.com'
		};
		const timeout = setTimeout(() => {
			dispatch({
				type: UPDATE_CURRENTINFO,
				state: {
					userInfo: myUserInfo
				}
			});
			clearTimeout(timeout);
		}, 3000);

		// getCurrentUser()
		//   .then((data: any) => {
		//     if (data && data.data) {
		//       myUserInfo = {};//
		//       dispatch({
		//         type: UPDATE_CURRENTINFO,
		//         state: {
		//           userInfo: myUserInfo,
		//           companyInfo: myCompanyInfo
		//         }
		//       });
		//     }
		//   })
		//   .catch(() => {

		//   });
	}, []);

	return <GlobalContext.Provider value={{ state, dispatch }}>{props.children}</GlobalContext.Provider>;
};

export default Provider;
